package com.elong.qadev.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.elong.qadev.entity.Log_TaskInfo;
import com.elong.qadev.entity.TaskInfo;
import com.elong.qadev.entity.User;
import com.elong.qadev.model.CaseInfo;
import com.elong.qadev.model.LastTaskInfo;
import com.elong.qadev.service.LogServiceI;
import com.elong.qadev.service.TaskServiceI;
import com.elong.qadev.task.QuartzManager;
import com.elong.qadev.tool.DateUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * @ClassName: TaskConfigAction
 * @Description: TODO(TASK相关action操作)
 * @author kangchen
 * @date 2015年10月3日
 *
 */
@ParentPackage("all")
public class TaskConfigAction extends ActionSupport {
	Logger logger = Logger.getLogger(TaskConfigAction.class);
	private static final long serialVersionUID = 1L;
	private ArrayList<TaskInfo> til = new ArrayList<TaskInfo>();
	private ArrayList<CaseInfo> cil = new ArrayList<CaseInfo>();
	private TaskInfo ti;

	@Autowired
	public TaskServiceI taskService;
	@Autowired
	public LogServiceI logService;

	public ArrayList<TaskInfo> getTil() {
		return til;
	}

	public void setTil(ArrayList<TaskInfo> til) {
		this.til = til;
	}

	public ArrayList<CaseInfo> getCil() {
		return cil;
	}

	public void setCil(ArrayList<CaseInfo> cil) {
		this.cil = cil;
	}

	public TaskInfo getTi() {
		return ti;
	}

	public void setTi(TaskInfo ti) {
		this.ti = ti;
	}

	@Action(value = "getTaskPageInfo", results = { @Result(name = "success", location = "/runTask/taskConfig.jsp", type = "dispatcher") })
	public String getTaskPageInfo() {
		logger.info("获取TASK页面配置信息");
		til = taskService.getTaskInfo();
		cil = taskService.getHttpCaseInfo();
		return "success";
	}

	/**
	 * 
	 * @Title: saveTaskInfo
	 * @Description: TODO(保存并动态增加TASK任务)
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "saveTaskInfo", results = { @Result(name = "success", location = "/runTask/getTaskInfo.jsp", type = "dispatcher") })
	public String saveTaskInfo() {
		User u = (User) ActionContext.getContext().getSession().get("user");
		ti.setConfiger(u.getName());
		ti.setCreateDate(new Date());
		logger.info("需要存入的TaskInfo是：" + ti.toString());
		if (taskService.saveTaskInfo(ti)) {
			QuartzManager.addJob(ti.getTaskName(),
					"com.elong.qadev.task.RunCaseJob", ti.getTimeConfig(), ti);
			return "success";
		} else {
			return "success";
		}
	}

	/**
	 * 
	 * @Title: deleteTaskInfo
	 * @Description: TODO(删除并动态减掉TASK任务)
	 * @param @return
	 * @param @throws Exception 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "deleteTaskInfo", results = { @Result(name = "success", location = "/runTask/getTaskInfo.jsp", type = "dispatcher") })
	public String deleteTaskInfo() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("UTF-8");
		String ids = new String(
				(request.getParameter("id")).getBytes("iso-8859-1"), "UTF-8");
		int id = Integer.parseInt(ids);
		TaskInfo tempTi = taskService.getTaskInfoById(id);
		logger.info("需要删除的TaskInfo-id是：" + id);
		if (taskService.deleteTaskInfo(id)) {
			QuartzManager.removeJob(tempTi.getTaskName());
			return "success";
		} else {
			return "success";
		}
	}
	/**
	 * results = { @Result(name = "success", type = "json") }
	* @Title: getLastTaskInfo
	* @Description: TODO(返回LASTTASKINFO)
	* @param @return
	* @param @throws Exception    参数
	* @return String    返回类型
	* @throws
	 */
	@Action(value = "getLastTaskInfo")
	public void getLastTaskInfo() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("UTF-8");
		String taskIdStr = request.getParameter("taskId");
		int taskId = Integer.parseInt(taskIdStr);
		logger.info("需要获取信息的TASKID是：" + taskId);
		LastTaskInfo lti = new LastTaskInfo();

		TaskInfo ti = taskService.getTaskInfoById(taskId);
		Log_TaskInfo logti = logService.getLogTaskInfoByBatchNumber(ti
				.getLastBatchNumber());

		lti.setTaskName(ti.getTaskName());
		lti.setTimeConfig(ti.getTimeConfig());
		lti.setLastBatchNumber(ti.getLastBatchNumber());
		lti.setLastRunTime(DateUtils.formatDate((logti.getStartDate())));
		lti.setMailTo(ti.getMailTo());
		lti.setDescription(ti.getDescription());
		lti.setContains(ti.getContains());

		String lastTaskInfo = JSON.toJSONString(lti, true);

		logger.info("获取到的json字符串是：" + lastTaskInfo.toString());
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(lastTaskInfo);
		out.flush();
		out.close();
	}

}
